﻿using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Utilities;

namespace Eneta.Portal.Controls
{
    public class ModerationControl : UserControl
    {
        #region UI
        
        protected HtmlGenericControl ModerationContainer;
        protected TextBox RejectReasonField;
        protected Label ModerationStatus;
        protected Button ChangeModerationItem;
        protected Button AcceptModerationItem;
        protected Button RejectModerationItem;
        protected HtmlGenericControl RejectStatus;
        protected HtmlGenericControl ModerationStatusComment;
        
        #endregion
        
        public bool RequireAdministrator { get; set; }
        public bool AllowEdit { get; set; }
        public string ModerationWebUrl { get; set; }
        public string EditFormUrl { get; set; }

        private SPUser CurrentUser
        { 
            get
            {
                return SPContext.Current.Web.CurrentUser;
            }
        }
        private bool IsAdmin
        { 
            get
            {
                if (CurrentUser == null)
                    return false;
                return CurrentUser.IsSiteAdmin;
            }
        }

        private bool IsAuthor
        {
            get
            {
                if (_item == null)
                    return false;
                if (CurrentUser == null)
                    return false;
                var authorValue = _item[SPBuiltInFieldId.Author];
                if (authorValue == null)
                    return false;
                var author = new SPFieldUserValue(SPContext.Current.Web, authorValue.ToString());
                if (author == null)
                    return false;
                return CurrentUser.ID == author.User.ID;
            }
        }
        public int ItemId { get; set; }
        
        private Guid ListId { get; set; }

        private SPListItem _item;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _item = GetModeratedItem();
            if (_item == null)
                return;
            if (CurrentUser == null)
                ModerationContainer.Visible = false;
            if (!IsAdmin && !IsAuthor)
                ModerationContainer.Visible = false;
            if (!AllowEdit)
                ChangeModerationItem.Visible = false;
            if (IsAuthor && !IsAdmin) 
            {
                AcceptModerationItem.Visible = false;
                RejectModerationItem.Visible = false;
                RejectStatus.Visible = false;
            }
            if (_item.ModerationInformation != null)
            {
                if (_item.ModerationInformation.Status == SPModerationStatusType.Approved)
                {
                    ModerationStatus.Text = "Kinnitatud";
                    ModerationStatus.Style.Add(HtmlTextWriterStyle.Color, "green");
                    var comment = _item.ModerationInformation.Comment;
                    if (IsAuthor || IsAdmin)
                    {
                        if (!string.IsNullOrEmpty(comment))
                        {
                            ModerationStatusComment.InnerText = "";
                            ModerationStatusComment.InnerText += "(" + comment + ")";
                        }
                    }
                }
                else
                {
                    if (_item.ModerationInformation.Status == SPModerationStatusType.Denied)
                    {
                        var comment = _item.ModerationInformation.Comment;
                        ModerationStatus.Text = "Tagasilükatud";
                        ModerationStatus.Style.Add(HtmlTextWriterStyle.Color, "red");
                        if (IsAuthor || IsAdmin)
                        {
                            if (!string.IsNullOrEmpty(comment))
                            {
                                ModerationStatusComment.InnerText = "";
                                ModerationStatusComment.InnerText += "(" + comment + ")";
                            }
                        }
                    }
                    else
                    {
                        ModerationStatus.Text = "Kinnitamisel";
                        ModerationStatus.Style.Add(HtmlTextWriterStyle.Color, "#ffcc00");
                    }
                }
            }
        }

        private SPListItem GetModeratedItem()
        {
            if (ItemId == 0 || string.IsNullOrEmpty(ModerationWebUrl))
                return null;
            SPListItem item = null;
            using (SPSite site = SPContext.Current.Site)
            {
                using (SPWeb web = site.OpenWeb(ModerationWebUrl))
                {
                    if (web == null)
                        return null;
                    var pagesListId = PublishingWeb.GetPagesListId(web);
                    var repository = new ModerationRepository(web);
                    ListId = PublishingWeb.GetPagesListId(web);
                    item = repository.GetItemBy(ItemId, ListId, ModerationWebUrl);
                    if (item != null)
                        return item;
                }
            }
            return null;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ChangeModerationItem.Click += ChangeModerationItem_Click;
            AcceptModerationItem.Click += AcceptModerationItem_Click;
            RejectModerationItem.Click += RejectModerationItem_Click;
        }

        public void RejectModerationItem_Click(object sender, EventArgs e)
        {
            var repository = new ModerationRepository(SPContext.Current.Web);
            var moderated = repository.DeclineItem(ItemId, ListId, ModerationWebUrl, RejectReasonField.Text);
            if (moderated)
            {
                ModerationStatus.Text = "Tagasilükatud";
                ModerationStatus.Style.Add(HtmlTextWriterStyle.Color, "red");

                if (_item != null)
                {
                    var user = new SPFieldUserValue(_item.ParentList.ParentWeb, _item["RealAuthor"] as string);
                    var body = "<html><body style='font-family:arial;font-size:10pt'><p>Hei " + user.User.Name +
                               "!</p>";
                    body += "<p>Sinu lisatud \"" + _item.Title + "\" andmeid ei kinnitatud.</p>";
                    if (!string.IsNullOrEmpty(RejectReasonField.Text))
                        body += "<p>Administraatori selgitus: " + RejectReasonField.Text + "</p>";

                    body += "<p>Tervitustega,<br/>";
                    body += "Eneta tiim</p>";
                    body +=
                        "<a href=\"http://www.eneta.ee\"><img src=\"http://www.eneta.ee/SiteCollectionImages/logod/eneta_logo_250x78_sinine.png\" border=\"0\"></a>";
                    body += "</body></html>";
                    string emailTitle = string.Empty;
                    switch (_item.ContentType.Name)
                    {
                        case "Raamat":
                            emailTitle = "Raamatu tagasilükkamine";
                            break;
                        case "Ajakiri":
                            emailTitle = "Ajakirja tagasilükkamine ";
                            break;
                        default:
                            emailTitle = "Sisu kinnitamine";
                            break;
                    }
                    SPUtility.SendEmail(_item.ParentList.ParentWeb, false, false, user.User.Email, emailTitle, body);
                    SPUtility.SendEmail(_item.ParentList.ParentWeb, false, false, "abi@eneta.ee", emailTitle, body);
                }
                Response.Redirect(Request.RawUrl, false);
                return;
            }
        }

        public void AcceptModerationItem_Click(object sender, EventArgs e)
        {
            bool success = false;
            if (_item != null)
            {
                var control = Parent.FindControl("LiteratureTagsSelection") as TagsSelectionControl;
                if (control != null)
                    success = control.SaveŚelectedKeywords(_item);
                if (_item.ModerationInformation.Status == SPModerationStatusType.Approved)
                {
                    Response.Redirect(Request.RawUrl, false);
                    return;
                }
            }
            var repository = new ModerationRepository(SPContext.Current.Web);
            var moderated = repository.ApproveItem(ItemId, ListId, ModerationWebUrl, RejectReasonField.Text);
            if (moderated)
            {
                ModerationStatus.Text = "Kinnitatud";
                ModerationStatus.Style.Add(HtmlTextWriterStyle.Color, "green");
                if (_item != null)
                {
                    var user = new SPFieldUserValue(_item.ParentList.ParentWeb, _item["RealAuthor"] as string);
                    var body = "<html><body style='font-family:arial;font-size:10pt'><p>Hei " + user.User.Name +
                               "!</p>";
                    body += "<p>Sinu lisatud \"" + _item.Title + "\" andmed kinnitati.</p>";
                    body += "<p>Tervitustega,<br/>";
                    body += "Eneta tiim</p>";
                    body +=
                        "<a href=\"http://www.eneta.ee\"><img src=\"http://www.eneta.ee/SiteCollectionImages/logod/eneta_logo_250x78_sinine.png\" border=\"0\"></a>";
                    body += "</body></html>";
                    string emailTitle = string.Empty;
                    switch(_item.ContentType.Name)
                    {
                        case "Raamat": 
                            emailTitle = "Raamatu kinnitamine";
                            break;
                        case "Ajakiri" :
                            emailTitle = "Ajakirja kinnitamine";
                            break;
                        default:
                            emailTitle = "Sisu kinnitamine";
                            break;
                    }
                    SPUtility.SendEmail(_item.ParentList.ParentWeb, false, false, user.User.Email, emailTitle, body);
                    SPUtility.SendEmail(_item.ParentList.ParentWeb, false, false, "abi@eneta.ee", emailTitle, body);
                }
            }
            Response.Redirect(Request.RawUrl, false);
        }

        public void ChangeModerationItem_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(EditFormUrl) && ItemId != 0)
                Response.Redirect(EditFormUrl + "?ID=" + ItemId);
        }
    }
}
